const { ethers } = require("hardhat");

async function main() {
    console.log("🔗 检查 Ganache 连接...\n");

    try {
        // 获取网络信息
        const network = await ethers.provider.getNetwork();
        console.log(`📋 网络信息:`);
        console.log(`  链ID: ${network.chainId}`);
        console.log(`  网络名称: ${network.name}`);

        // 获取区块号
        const blockNumber = await ethers.provider.getBlockNumber();
        console.log(`📦 当前区块: ${blockNumber}`);

        // 获取账户列表
        const accounts = await ethers.provider.listAccounts();
        console.log(`👤 可用账户: ${accounts.length}`);
        accounts.forEach((account, index) => {
            console.log(`  ${index}: ${account}`);
        });

        // 检查账户余额
        if (accounts.length > 0) {
            const balance = await ethers.provider.getBalance(accounts[0]);
            console.log(`💰 第一个账户余额: ${ethers.formatEther(balance)} ETH`);
        }

        console.log("\n✅ Ganache 连接成功！");

    } catch (error) {
        console.log("❌ 连接 Ganache 失败:", error.message);
        console.log("\n💡 请确保:");
        console.log("1. Ganache Docker 容器正在运行");
        console.log("2. Ganache 运行在端口 8545");
        console.log("3. 网络配置正确");
    }
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error("检查失败:", error);
        process.exit(1);
    });